package com.asia5b.a5mall.member.fragment

import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.launcher.ARouter
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.member.activity.accout.ThirdProfileActivity
import com.asia5b.a5mall.member.R
import com.asia5b.a5mall.member.databinding.FragmentThirdprofileloginBinding
import com.asia5b.a5mall.middleware.base.SimpleDialogFragment
import com.asia5b.a5mall.middleware.base.SimpleFragment
import com.asia5b.a5mall.middleware.config.GlobalValue
import com.asia5b.a5mall.middleware.event.LoginEvent
import com.asia5b.a5mall.middleware.logic.viewmodel.member.AccoutVM
import com.asia5b.a5mall.middleware.model.member.CountryModel
import com.asia5b.a5mall.middleware.model.bean.CheckSmsBean
import com.asia5b.a5mall.middleware.model.bean.CheckSmsType
import com.asia5b.a5mall.middleware.model.bean.ImageCodeType
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.middleware.widget.BaseTextWatcher
import kotlinx.android.synthetic.main.fragment_thirdprofilelogin.*

/**
 * Created by zhangyuncai on 2020/5/18.
 */
class ThirdProfileLoginFragment : SimpleFragment<AccoutVM, FragmentThirdprofileloginBinding>() {

    override val viewModelClazz: Class<AccoutVM>
        get() = AccoutVM::class.java

    override fun getDataBinding(container: ViewGroup?): FragmentThirdprofileloginBinding {
        thirdProfileActivity = requireActivity() as ThirdProfileActivity
        return FragmentThirdprofileloginBinding.inflate(layoutInflater, container, false)
    }

    val textWatcher = object : BaseTextWatcher() {
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            checkInput()
        }
    }


    lateinit var thirdProfileActivity: ThirdProfileActivity

    override fun initView() {
        GlobalValue.setLength(et_login_code)
        changeLoginType()
    }

    fun changeLoginType() {
        ll_login_userlogin.visibility = (rb_login_userlogin.isChecked).judge(View.VISIBLE, View.GONE)
        ll_login_smslogin.visibility = (!rb_login_userlogin.isChecked).judge(View.VISIBLE, View.GONE)
        bt_login_submit.setText((rb_login_userlogin.isChecked).judge(R.string.登录, R.string.发送验证码))

        checkInput()
        et_login_code.setText("")
    }

    fun checkInput() {
        val code = et_login_code.text.trim().toString()
        if (rb_login_userlogin.isChecked) {//账号密码登录
            val username = et_login_username.text.trim().toString()
            val password = et_login_password.text.trim().toString()
            iv_login_clear_username.visibility = (username.isNotEmpty()).judge(View.VISIBLE, View.GONE)
            iv_login_clear_password.visibility = (username.isNotEmpty()).judge(View.VISIBLE, View.GONE)
            bt_login_submit.isEnabled = (username.isNotEmpty()) && (password.isNotEmpty()) && code.length == GlobalValue.imgCodeLength
        } else {//手机号登录
            val mobile = et_login_mobile.text.trim().toString()
            iv_login_clear_mobile.visibility = (mobile.isNotEmpty()).judge(View.VISIBLE, View.GONE)
            //国家手机区号
            val countryCode = tv_login_country_code.text.toString().trim().replace("+", "")
            bt_login_submit.isEnabled = WValidatorUtil.isPhoneNumber(mobile, countryCode) && code.length == GlobalValue.imgCodeLength
        }
    }

    override fun initEvent() {
        /*切换登录类型*/
        rg_login_logintype.setOnCheckedChangeListener { group, checkedId ->
            changeLoginType()
        }
        et_login_username.addTextChangedListener(textWatcher)
        et_login_password.addTextChangedListener(textWatcher)
        et_login_mobile.addTextChangedListener(textWatcher)
        et_login_code.addTextChangedListener(textWatcher)
        /**设置密码显示状态*/
        iv_login_eye_password.setOnClickListener {
            if (et_login_password.transformationMethod is PasswordTransformationMethod) {
                et_login_password.transformationMethod = HideReturnsTransformationMethod.getInstance()
                iv_login_eye_password.setImageResource(R.drawable.ic_eye_close)
                iv_login_eye_password.requestFocus()
            } else {
                et_login_password.transformationMethod = PasswordTransformationMethod.getInstance()
                iv_login_eye_password.setImageResource(R.drawable.ic_eye)
                iv_login_eye_password.requestFocus()
            }
        }
        /**清空账号*/
        iv_login_clear_username.setOnClickListener {
            et_login_username.setText("")
        }
        /**清空密码*/
        iv_login_clear_password.setOnClickListener {
            et_login_password.setText("")
        }
        /**清空手机号*/
        iv_login_clear_mobile.setOnClickListener {
            et_login_mobile.setText("")
        }
        /*提交*/
        bt_login_submit.setOnClickListener {
            submit()
        }
        /*重新加载验证码*/
        iv_login_code.setOnClickListener {
            loadImageCode()
        }
        // 选择区号
        if (GlobalValue.isDebug) {
            tv_login_country_code.text = "+86"
            checkInput()
        }
        ll_login_country_code.setOnClickListener {
            InputMethodUtils.closeKeyBoard(requireActivity())
            val baseDialogFragment = ARouter.getInstance().build(ActCons.SelectCountryPhoneCodeDF).navigation()
            if (baseDialogFragment == null) {
                return@setOnClickListener
            }
            val selectPhoneCodeDF = baseDialogFragment as SimpleDialogFragment<*, *>
            selectPhoneCodeDF.show(childFragmentManager, "SelectCountryPhoneCodeDF")
            selectPhoneCodeDF.setSureClick<CountryModel> {
                tv_login_country_code.text = "+${it.country_code}"
                checkInput()
            }
        }
    }

    override fun lazyFetchData() {
        loadImageCode()
    }

    fun loadImageCode() {
        mViewModel.loadImageCode(ImageCodeType.LOGIN)
    }

    fun submit() {
        val code = et_login_code.text.trim().toString()
        if (rb_login_userlogin.isChecked) {//账号密码登录
            val username = et_login_username.text.trim().toString()
            val password = et_login_password.text.trim().toString()
            //todo 用户密码登录->登录成功
            mViewModel.userLogin(username, password, code)
        } else {//手机号登录
            val mobile = et_login_mobile.text.trim().toString()
            //todo 手机号登录->发送短信->短信验证界面成功->登录成功
            mViewModel.sendSms(
                    CheckSmsBean(CheckSmsType.DYNAMIC_LOGIN).apply {
                        this.mobile = mobile
                        this.imageCode = code
                        this.areaCode = tv_login_country_code.text.toString().trim().replace("+", "")
                    }
            )
        }
    }
    override fun startObserver() {
        /**
         * 账号密码登录
         */
        mViewModel.loginSuccessResultLiveData.observe(this, Observer {
            getEventBus().post(LoginEvent())
            thirdProfileActivity.addFragment()
        })
        mViewModel.loadImageCodeLiveData.observe(this, Observer {
            it?.let {
                iv_login_code.setImageBitmap(it)
            }
            if (it == null) {
                /**加载验证码*/
                mViewModel.loadImageCode(ImageCodeType.LOGIN)
            }

        })
        /**
         * 发送手机号成功
         */
        mViewModel.sendSmsLiveData.observe(this, Observer {
            push(ActCons.CheckSmsActivity, { postcard ->
                it.putParams(postcard)
            })
        })
        mViewModel.checkSmsCodeLiveData.observe(this, Observer {

        })
    }


}